/*

  cputhrottle - a utility to throttle the CPU speed from a default "powersave"
  configuration to a performance one to its full capacity - without the need
  to reboot or overclock the machine!

  This utility was written with a Raspberry Pi 4 in mind, but other SoCs could
  benefit from it, like the beefier RockPro or etc. Same principle. And TBH 
  any computer running Linux should work, actually, given its an interface of
  the Linux kernel.

  "Dude you could've written a shell script to do the same darn thing in 5min."
  - and also not have learnt anything new either. This is another opportunity
  to learn C and string formatting!

  Copyright 2022 kzimmermann <https://tilde.town/~kzimmermann> all rights 
  reserved.

  This program is Free Software licensed under the terms and conditions of the
  GNU GPL v3. See <https://www.gnu.org/licenses/> for more information.

 */

#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "specs.h"
#include "funcs.h"

// The main command to be run (as root) is:
// cpupower frequency-set --max 1500000 --governor performance
// You can check the clock from here:
// cat /sys/devices/system/cpu/cpu*/cpufreq/cpuinfo_cur_freq

int
main(int argc, char* argv[])
{
    long freq;

    // read content from file. It(should be about 20char max)
    freq = query_file(CPU_CUR_FILE);

    if (freq == -1) {
        printf("Unable to open '%s'\nDoes the file exist?\n", CPU_CUR_FILE);
        printf("Alternatively, are you root?\n");
        return 1;
    }

    printf("The current CPU frequency is %ld kHz\n", freq);

    freq = query_file(CPU_MAX_FILE);

    if (freq == -1) {
        printf("Unable to open '%s'\nDoes the file exist?\n", CPU_MAX_FILE);
        printf("Alternatively, are you root?\n");
        return 1;
    }

    // asprintf anyone??
    char *stmt;
    asprintf(&stmt, QUERY_COMMAND, freq); 
    
    // execute the query and free up resources regardless of failure.
    int sys_status = system(stmt);
    free(stmt);

    if (sys_status != 0) {
        printf("Error: could not change CPU frequency to %ld kHz.\n", freq);
        printf("This is most likely due to the lack of permissions (i.e. no root).\n");
        return 1;
    }

    printf("CPU frequency now set to %ld kHz.\n", freq);

    return 0;
}
